package Socker;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @Title: UDP
 * @Author 郑雨杭
 * @Package Socker
 * @Date 2024/7/10 12:03
 * @description: UDP服务器
 */
public class UDPServer {

    private DatagramSocket socket =null;

    public UDPServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    protected void start() throws IOException {
        System.out.println("服务器启动");
        while (true){
            byte[] rem = new byte[4096];
            DatagramPacket p = new DatagramPacket(rem,0,rem.length);
            socket.receive(p);
            String s = new String(p.getData(),0,p.getLength());
            String r = process(s);
            DatagramPacket ret = new DatagramPacket(r.getBytes(),r.getBytes().length,p.getSocketAddress());
            socket.send(ret);
            System.out.printf("[%s:%d],req=%s,resp=%s\n",p.getAddress().toString(),p.getPort(),s,r);
        }
    }

    protected String process(String s) {
        return s;
    }

    public static void main(String[] args) throws IOException {
        new UDPServer(9090).start();
    }
}
